package org.user.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.user.pojo.User;
import org.user.service.UserService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
	
	String name;
	String password;
	String type;
	String code;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	String target;
	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String execute() throws Exception {
		User user = userService.login(getName(), getPassword());
		ActionContext ctx = ActionContext.getContext();
		String rand = (String)ctx.getSession().get("rand");
		System.out.println(user);
		System.out.println(getCode());
		System.out.println(rand);
		if(user==null || !getCode().equals(rand) || !user.getType().equals(Integer.parseInt(getType())))
		{
			addActionMessage("");
			if(user == null || !user.getType().equals(Integer.parseInt(getType())))
				ctx.getSession().put("flag", "0");
			else
				ctx.getSession().put("flag", "1");
			System.out.println(ctx.getSession().get("flag"));
			return ERROR;
		}
		else if(user.getType()==0)
		{
			System.out.println(user.getName()+"00000");
			clearMessages();
			ctx.getSession().put("user", user);
			String url = ctx.getSession().get("url").toString();
			setTarget(url.substring(4));
			ctx.getSession().remove("flag");
			return SUCCESS;
		}
		else
		{
			clearMessages();
			ctx.getSession().put("user", user);
			String url = ctx.getSession().get("url").toString();
			return "manager";
		}
	}
}
